package com.yuwubao.hz_International.controllers.sys;

import com.yuwubao.hz_International.entities.AcountDetailEntity;
import com.yuwubao.hz_International.entities.ConsumerEntity;
import com.yuwubao.hz_International.entities.StoreEntity;
import com.yuwubao.hz_International.entities.vo.StoreDetailVo;
import com.yuwubao.hz_International.entities.vo.StoreVo;
import com.yuwubao.hz_International.services.AcountDetailService;
import com.yuwubao.hz_International.services.AppService;
import com.yuwubao.hz_International.services.ConsumerService;
import com.yuwubao.hz_International.services.StoreService;
import com.yuwubao.hz_International.util.Const;
import com.yuwubao.hz_International.util.PageUtil;
import com.yuwubao.hz_International.util.RestApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangyu on 2018/1/28.
 */
@RestController
@RequestMapping("/sys/storeManage")
@Transactional
@CrossOrigin
@Api(value = "后台接口")
public class StoreManageController {

    private final static Logger logger = LoggerFactory.getLogger(StoreManageController.class);

    @Autowired
    private StoreService storeService;

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private AcountDetailService acountDetailService;

    @Resource
    private AppService appService;

    /**
     * 获取商家列表
     * @param storeName 商家名
     * @param index  第几页
     * @param size  每页几条
     * @return
     */
    @GetMapping("/getStoreList")
    @ApiOperation(value = "获取商家列表")
    public RestApiResponse<PageUtil<StoreVo>> getStoreList(@ApiParam(required = false, value = "商家名")@RequestParam(defaultValue = "", required = false) String storeName,
                                                           @ApiParam(required = false, value = "第几页")@RequestParam(defaultValue = "1", required = false) int index,
                                                           @ApiParam(required = false, value = "每页几条")@RequestParam(defaultValue = "10", required = false) int size) {
        RestApiResponse<PageUtil<StoreVo>> result = new RestApiResponse<PageUtil<StoreVo>>();
        try {
            PageUtil<StoreVo> pageUtil = new PageUtil<StoreVo>();
            List<StoreVo> list = storeService.findStoreList(storeName, index-1, size);
            List<StoreVo> storeList = storeService.findStoreList(storeName, 0, 0);
            pageUtil.setTotalElements(storeList.size());
            pageUtil.setTotalPages(size, storeList.size());
            pageUtil.setIndex(index);
            pageUtil.setSize(size);
            pageUtil.setList(list);
            result.successResponse(Const.SUCCESS, pageUtil);
        } catch (Exception e) {
            logger.warn("获取商家列表异常", e);
            result.failedApiResponse(Const.FAILED, "获取专家列表异常");
        }
        return result;
    }

    /**
     * 获取商家详情
     * @param storeId  商家id
     * @return
     */
    @GetMapping("/findOne")
    @ApiOperation(value = "获取商家详情")
    public RestApiResponse<StoreDetailVo> findOne(@ApiParam(required = true, value = "商家id")@RequestParam int storeId) {
        RestApiResponse<StoreDetailVo> result = new RestApiResponse<StoreDetailVo>();
        try {
            StoreEntity storeEntity = storeService.findOne(storeId);
            if (storeEntity == null) {
                result.failedApiResponse(Const.FAILED, "当前商家不存在，请刷新再试");
                return result;
            }

            ModelMapper model = new ModelMapper();
            StoreDetailVo entityVo = model.map(storeEntity, StoreDetailVo.class);
            String photoUrl = storeEntity.getPhotoUrl() != null ? storeEntity.getPhotoUrl() : "";
            entityVo.setPhotoUrl(photoUrl);
            String[] imgArr = new String[3];
            imgArr[0] = storeEntity.getImageUrl1() != null?storeEntity.getImageUrl1():"";
            imgArr[1] = storeEntity.getImageUrl2() != null?storeEntity.getImageUrl2():"";
            imgArr[2] = storeEntity.getImageUrl3() != null?storeEntity.getImageUrl3():"";
            entityVo.setImageUrl(imgArr);

            result.successResponse(Const.SUCCESS, entityVo);
        } catch (Exception e) {
            logger.warn("获取商家详情异常", e);
            result.failedApiResponse(Const.FAILED, "获取专家详情异常");
        }
        return result;
    }

    /**
     * 更新商家信息
     * @param storeDetailVo
     * @return
     */
    @PostMapping("/updateStore")
    @ApiOperation(value = "更新商家信息")
    public RestApiResponse<StoreEntity> findOne(@RequestBody StoreDetailVo storeDetailVo) {
        RestApiResponse<StoreEntity> result = new RestApiResponse<StoreEntity>();
        try {
            StoreEntity storeEntity = storeService.findOne(storeDetailVo.getId());
            if (storeEntity == null) {
                result.failedApiResponse(Const.FAILED, "当前商家不存在，请刷新再试");
                return result;
            }
            ModelMapper model = new ModelMapper();
            StoreEntity entity = model.map(storeDetailVo, StoreEntity.class);
            String qrUrl = appService.createQrCode(entity);
            entity.setQrUrl(qrUrl);
            entity.setCreateTime(storeEntity.getCreateTime());
            String[] imageUrl = storeDetailVo.getImageUrl();
            if (imageUrl.length > 0) {
                for (int i = 0;i< imageUrl.length; i++) {
                    switch (i) {
                        case 0:
                            entity.setImageUrl1(imageUrl[i]);
                            break;
                        case 1:
                            entity.setImageUrl2(imageUrl[i]);
                            break;
                        case 2:
                            entity.setImageUrl3(imageUrl[i]);
                            break;
                    }
                }
            }
            StoreEntity newEntity = storeService.update(entity);
            result.successResponse(Const.SUCCESS, newEntity, "修改成功");
        } catch (Exception e) {
            logger.warn("修改商家详情异常", e);
            result.failedApiResponse(Const.FAILED, "修改专家详情异常");
        }
        return result;
    }

    /**
     * 删除商家
     * @param storeId 商家id
     * @return
     */
    @PostMapping("/deleteStore")
    @ApiOperation(value = "删除商家")
    public RestApiResponse<Boolean> deleteStore(@RequestBody Integer[] storeId) {
        RestApiResponse<Boolean> result = new RestApiResponse<Boolean>();
        try {
            for (int i: storeId) {
                StoreEntity storeEntity = storeService.delete(i);
                if (storeEntity == null) {
                    result.failedApiResponse(Const.FAILED, "商家不存在，删除失败");
                    return result;
                }
                //删除商家后更新会员信息
                ConsumerEntity consumerEntity = consumerService.findOne(storeEntity.getConsumerId());
                consumerEntity.setIsStore(0);
                consumerService.update(consumerEntity);
            }
            result.successResponse(Const.SUCCESS, true, "删除成功");
        } catch (Exception e) {
            logger.warn("删除商家异常", e);
            result.failedApiResponse(Const.FAILED, "删除商家异常");
        }
        return result;
    }


    /**
     * 获取商家资金明细
     * @param storeId  商家id
     * @param beginTime  开始时间
     * @param endTime  结束时间
     * @param index 第几页
     * @param size  每页几条
     * @return
     */
    @GetMapping("/getStoreFinancialDetails")
    @ApiOperation(value = "获取商家资金明细")
    public RestApiResponse<PageUtil<AcountDetailEntity>> getStoreFinancialDetails(@ApiParam(required = false, value = "商家id")@RequestParam(required = false, defaultValue = "0") int storeId,
                                                                                  @ApiParam(required = false, value = "开始时间")@RequestParam(required = false, defaultValue = "")String beginTime,
                                                                                  @ApiParam(required = false, value = "结束时间")@RequestParam(required = false, defaultValue = "")String endTime,
                                                                                  @ApiParam(required = false, value = "第几页")@RequestParam(required = false, defaultValue = "1") int index,
                                                                                  @ApiParam(required = false, value = "每页几条")@RequestParam(required = false, defaultValue = "10") int size) {
        RestApiResponse<PageUtil<AcountDetailEntity>> result = new RestApiResponse<PageUtil<AcountDetailEntity>>();
        try {
            StoreEntity storeEntity = storeService.findOne(storeId);
            if (storeEntity == null) {
                result.failedApiResponse(Const.FAILED, "查看的商家不存在,请刷新");
                return result;
            }
            int consumerId = storeEntity.getConsumerId();
            //添加分页
            PageUtil pageUtil = new PageUtil();
            pageUtil.setIndex(index);
            pageUtil.setSize(size);

            Map<String, String> map = new HashMap<String, String>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            List<AcountDetailEntity> list = acountDetailService.findFinancialDetails(map, pageUtil, consumerId);
            Integer financialDetailsSum = acountDetailService.findFinancialDetailsSum(map, consumerId);
            pageUtil.setTotalElements(financialDetailsSum);
            pageUtil.setTotalPages(size, financialDetailsSum);
            pageUtil.setBuyerName(storeEntity.getName());
            pageUtil.setList(list);
            result.successResponse(Const.SUCCESS, pageUtil);
        } catch (Exception e) {
            logger.warn("获取商家资金明细异常", e);
            result.failedApiResponse(Const.FAILED, "获取商家资金明细异常");
        }
        return result;
    }

    @PostMapping("stick")
    @ApiModelProperty("置顶")
    public RestApiResponse<Boolean> stick(@RequestParam int id){
        RestApiResponse<Boolean> restApiResponse = new RestApiResponse<>();
        storeService.stick(id);
        restApiResponse.successResponse(true);
        return restApiResponse;
    }

}
